from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.exceptions import ValidationError

from microerp.apps.base.forms import SignUpForm, SignInForm
from microerp.apps.base.models import Users

'''
登录界面
包含POST方法  即用户登录
'''
#Do sth when login
def login(request):
	if request.method == 'POST':
		form = SignInForm(request.POST)
		if form.is_valid():
			email = form.cleaned_data["email"]
			remember = form.cleaned_data["remember"]
			user = Users.objects.filter(email=email)[0]#取第一个 [0]
			userid = user.id
			'''
			set Cookie and Session
			The Cookie time should be same with Session time 
			'''
			expire_time = 36000
			if remember:
				expire_time = 36000 * 7
			request.session["userid"] = userid
			response = HttpResponseRedirect('/index/')
			response.set_cookie('userid',userid,expire_time)
			return response
		else:
			return render(request,'base/signin.html',{'form':form,'error':True})
	else:
		return render(request, 'base/signin.html')


def signin(request):
	return login(request)

'''
注册界面
当方法为post即代表用户注册
'''
def signup(request):
	if request.method == 'POST':
		form = SignUpForm(request.POST)
		#binding data
		if form.is_valid():
			user = Users()
			user.username = form.cleaned_data["email"]
			user.email = form.cleaned_data["email"]
			user.password = form.cleaned_data["password1"]
			user.save()
			return render(request, 'base/signup.html',{'sign':True,'form':form})
		else:
			return render(request, 'base/signup.html',{'sign':False,'form':form,'error':True})
	else:
		return render(request, 'base/signup.html')

'''
测试用
'''
def show(request):
	users = Users.objects.all()
	content = ''
	for user in users:
		content = content + str(user.email) + "<br>"
	return HttpResponse(content)

'''
跳转到index页面
'''
def index(request):
	userid = request.session.get('userid','anybody')
	if userid != 'anybody':
		return render(request, 'index.html')
	else:
		return render(request, 'base/signin.html')


'''
判断用户是否登录
'''
def islogin(request):
	userid = request.session.get("userid",0)
	if userid is 0:
		return False
	else:
		return True

'''
获取当前用户ID
'''
def get_user_id(request):
	return request.session.get("userid",0)